<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 详情弹窗 -->
    <div v-if="showPopup" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg w-[800px] max-h-[90vh] flex flex-col">
        <!-- 标题区域 -->
        <div class="flex justify-between items-center p-6 border-b">
          <h2 class="text-2xl font-bold">比赛参与详情</h2>
          <button class="text-gray-500 hover:text-gray-700" @click="closePopup">
            <i class="fas fa-times text-xl"></i>
          </button>
        </div>

        <!-- 内容区域 -->
        <div class="flex-1 overflow-y-auto p-6">
          <!-- 比赛基本信息 -->
          <div class="mb-8">
            <h3 class="text-lg font-semibold mb-4 flex items-center">
              <i class="fas fa-trophy text-yellow-500 mr-2"></i>
              比赛基本信息
            </h3>
            <div class="grid grid-cols-2 gap-4">
              <div class="flex items-start">
                <span class="text-gray-500 bold-black" style="width:200px">比赛名称：</span>
                <span class="font-medium">{{ currentCompetition.competitionName }}</span>
              </div>
              <div class="flex items-start">
                <span class="text-gray-500 w-24 bold-black">主办方：</span>
                <span class="font-medium">{{ currentCompetition.competitionOrganizer }}</span>
              </div>
              <div class="flex items-start">
                <span class="text-gray-500 w-24 bold-black">比赛类型：</span>
                <span class="font-medium">{{ currentCompetition.competitionType }}</span>
              </div>
              <div class="flex items-start">
                <span class="text-gray-500 w-24 bold-black">比赛日期：</span>
                <span class="font-medium">{{ formatDate(currentCompetition.competitionStartTime) }}</span>
              </div>
            </div>
          </div>

          <!-- 参与信息 -->
          <div class="mb-8">
            <h3 class="text-lg font-semibold mb-4 flex items-center">
              <i class="fas fa-user-friends text-blue-500 mr-2"></i>
              参与信息
            </h3>
            <div class="grid grid-cols-2 gap-4">
              <div class="flex items-start">
                <span class="text-gray-500 w-24 bold-black">参赛角色：</span>
                <span class="font-medium">{{ currentCompetition.name }}</span>
              </div>
              <div class="flex items-start">
                <span class="text-gray-500 w-24 bold-black">所在团队：</span>
                <span class="font-medium">{{ currentCompetition.schoolName }}</span>
              </div>
              <div class="flex items-start">
                <span class="text-gray-500 w-24 bold-black">结束时间：</span>
                <span class="font-medium">{{ formatDate(currentCompetition.competitionEndTime) }}</span>
              </div>
            </div>
          </div>

          <!-- 获奖信息 -->
          <div class="mb-8">
            <h3 class="text-lg font-semibold mb-4 flex items-center">
              <i class="fas fa-medal text-yellow-500 mr-2"></i>
              获奖信息
            </h3>
            <div class="grid grid-cols-2 gap-4">
              <div class="flex items-start">
                <span class="text-gray-500 w-24 bold-black">奖项级别：</span>
                <span class="font-medium text-red-600">{{ currentCompetition.competitionAwardLevelName }}</span>
              </div>


            </div>
          </div>

          <!-- 证明材料 -->
          <div>
            <h3 class="text-lg font-semibold mb-4 flex items-center">
              <i class="fas fa-file-alt text-green-500 mr-2"></i>
              证明材料
            </h3>
            <div class="grid grid-cols-2 gap-4">
              <div v-for="(cert, index) in certificates" :key="index" class="relative group">
                <div class="border rounded-lg p-4 hover:shadow-lg transition-shadow">
                  <img :src="cert.url" :alt="cert.name" class="w-full h-40 object-cover rounded-lg mb-2"
                    @click="previewImage(cert.url)" />
                  <div class="text-sm">
                    <p class="font-medium truncate">{{ cert.name }}</p>
                    <p class="text-gray-500">上传时间：{{ formatDate(cert.uploadTime) }}</p>
                  </div>
                  <button
                    class="absolute top-2 right-2 bg-white rounded-full p-2 shadow-md opacity-0 group-hover:opacity-100 transition-opacity"
                    @click="downloadCertificate(cert)">
                    <i class="fas fa-download text-gray-600"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部操作栏 -->
        <div class="border-t p-6 flex justify-end space-x-4">
          <button class="px-4 py-2 bg-blue-600 text-white flex items-center" @click="exportPDF">
            <i class="fas fa-file-pdf mr-2"></i>
            导出 PDF
          </button>
          <button class="px-4 py-2 border border-gray-300 text-gray-700 flex items-center" @click="closePopup">
            <i class="fas fa-times mr-2"></i>
            关闭
          </button>
        </div>
      </div>

      <!-- 图片预览 -->
      <div v-if="previewUrl" class="fixed inset-0 bg-black bg-opacity-90 flex items-center justify-center z-50"
        @click="previewUrl = ''">
        <img :src="previewUrl" alt="预览图片" class="max-w-[90%] max-h-[90vh] object-contain" />
      </div>
    </div>

    <div class="ml-20" style="min-width: 1080px;">
      <div ref="contentDiv" class="bg-white rounded-lg shadow-sm p-6"
        style="min-width: 81vw; margin-left: 20vw; height: 96vh;margin-top: 2vh;">
        <!-- 状态筛选 -->
        <div class="flex gap-4 mb-6">
          <button v-for="tab in tabs" :key="tab.value" @click="handleTabClick(tab)" :class="{
            'bg-blue-500 text-white': currentTab === tab.value,
            'bg-gray-100 text-gray-600': currentTab !== tab.value,
            'rounded-md': true
          }" class="px-4 py-2 text-sm font-medium whitespace-nowrap">
            {{ tab.label }}
          </button>
        </div>
        <!-- 表格 -->
        <div class="overflow-x-auto table-container" style="max-height: 500px; overflow-y: auto;">
          <table class="min-w-full">
            <thead class="bg-gray-50 sticky top-0 z-10">
              <tr>
                <th v-for="header in tableHeaders" :key="header"
                  class="py-3.5 px-4 text-left text-sm font-medium text-gray-900">
                  {{ header }}
                </th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-200">
              <tr v-for="item in tableData" :key="item.id">
                <td class="py-4 px-4 text-sm text-gray-900" style="max-width: 250px; overflow: hidden; text-overflow: ellipsis;">{{ item.competitionName }}</td>
                <td class="py-4 px-4 text-sm text-gray-600">{{ item.name }}</td>
                <td class="py-4 px-4 text-sm text-gray-600">{{ item.competitionType }}</td>
                <td class="py-4 px-4 text-sm text-gray-600">{{ item.competitionAwardLevelName }}</td>
                <td class="py-4 px-4 text-sm text-gray-600">{{ item.competitionOrganizer }}</td>
                <td class="py-4 px-4">
                  <div class="flex items-center gap-3">
                    <template v-if="currentTab === 'pending'">
                      <button @click="approve(item)"
                        class="px-3 py-1 text-sm text-white bg-green-500 rounded-md whitespace-nowrap">通过</button>
                      <button @click="reject(item)"
                        class="px-3 py-1 text-sm text-white bg-red-500 rounded-md whitespace-nowrap">不通过</button>
                    </template>
                    <button @click="openDetail(item)"
                      class="px-3 py-1 text-sm text-white bg-blue-500 rounded-md whitespace-nowrap">详情</button>
                    <template v-if="currentTab === 'approved'">
                      <span class="flex items-center gap-1 text-green-600">
                        <i class="iconfont icon-gou1"></i>
                        <i class="fas fa-check-circle"></i>
                        <span class="text-sm">已通过</span>
                      </span>
                    </template>
                    <template v-if="currentTab === 'rejected'">
                      <span class="flex items-center gap-1 text-red-600">
                        <i class="fas fa-times-circle"></i>
                        <i class="iconfont icon-chacha"></i>
                        <span class="text-sm">未通过</span>
                      </span>
                    </template>
                  </div>
                </td>
              </tr>
            </tbody>

          </table>
        </div>
        <!-- 分页 -->
        <div class="flex items-center justify-between mt-6">
          <div class="flex items-center gap-2">
            <div class="relative">
              <div class="px-3 py-1 text-sm border rounded-md !rounded-button whitespace-nowrap flex items-center gap-2">
                共 {{ total }} 条信息
                <i class="fas fa-chevron-down text-xs"></i>
              </div>
            </div>
          </div>

          <div class="flex item-center gap-2">
            <el-pagination background v-model:current-page="pageNum" v-model:page-size="pageSize"
              :page-sizes="[5, 10, 15, 20]" layout="sizes, prev, pager, next" :total="total"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
  

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { getCompetitionReview, competitionReview } from "@/api/teacher/competition";

const contentDiv = ref();

let pageNum = ref(1);
let pageSize = ref(5);
let total = ref(0); // 总数据条数

// 日期格式化方法
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};
// 分页大小变化时触发
const handleSizeChange = (val) => {
  pageSize.value = val;
  getCompetitionList();
}

// 分页页码变化时触发
const handleCurrentChange = (val) => {
  pageNum.value = val;
  getCompetitionList();
}

const previewUrl = ref('');
const showPopup = ref(false);
const data = ref({});
const certificates = ref([
  {
    name: '全国大学生数学建模竞赛一等奖证书.pdf',
    url: 'https://ai-public.mastergo.com/ai/img_res/029e4d078ed517e8e625619bbf1e2a17.jpg',
    uploadTime: '2023-10-21 14:30',
  },
  {
    name: '比赛参与证明.pdf',
    url: 'https://ai-public.mastergo.com/ai/img_res/9e613bb6ed66ee125c88d350144a7d4d.jpg',
    uploadTime: '2023-10-21 14:31',
  }
]);

const previewImage = (url) => {
  previewUrl.value = url;
};

const downloadCertificate = (cert) => {
  // 下载证书的逻辑
};

const exportPDF = () => {
  // 导出PDF的逻辑
};

const currentTab = ref('pending');
const tabs = [
  { label: "审核中", value: "pending", status: 0 },
  { label: "已通过", value: "approved", status: 1 },
  { label: "未通过", value: "rejected", status: 2 },
];
const tableHeaders = ['比赛名称', '参与学生', '比赛类型', '获奖等级', '主办方', '操作'];
const currentCompetition = reactive({
  competitionAwardLevelName: '',
  competitionEndTime: '',
  competitionName: '',
  competitionOrganizer: '',
  competitionStartTime: '',
  competitionType: '',
  name: '',
  photoMaterials: '',
  schoolName: '',
  status: '',

});

const openDetail = (item) => {
  currentCompetition.competitionAwardLevelName = item.competitionAwardLevelName;
  currentCompetition.competitionEndTime = item.competitionEndTime;
  currentCompetition.competitionName = item.competitionName;
  currentCompetition.competitionOrganizer = item.competitionOrganizer;
  currentCompetition.competitionStartTime = item.competitionStartTime;
  currentCompetition.competitionType = item.competitionType;
  currentCompetition.name = item.name;
  currentCompetition.photoMaterials = item.photoMaterials;
  currentCompetition.schoolName = item.schoolName;
  currentCompetition.status = item.status;
  showPopup.value = true;

  // 如果有图片，则设置放大图片的 URL
  if (data.photoMaterials) {
    enlargeImageUrl.value = data.photoMaterials;
  }
};
//关闭详情弹窗
const closePopup = () => {
  showPopup.value = false;
};

// 打开放大图片
const openEnlargeModal = (url) => {
  enlargeImageUrl.value = url;
  showEnlargeModal.value = true;
};

// 关闭放大图片
const closeEnlargeModal = () => {
  showEnlargeModal.value = false;
};
const handleClickOutside = (event) => {
  if (!event.target.closest('.bg-white') && showEnlargeModal.value) {
    closeEnlargeModal();
  }
};

//查询数据列表
let tableData = ref([]);
function getCompetitionList() {
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    status: currentTab.value === 'pending' ? 0 : currentTab.value === 'approved' ? 1 : 2,
  };
  getCompetitionReview(params).then((response) => {
    console.log("列表数据返回", response);
    tableData.value = response.rows; 
    total.value = response.total; 
  });
}

//根据状态查询数据
const handleTabClick = (tab) => {
  currentTab.value = tab.value;
  let status = tabs.filter((x) => x.value === tab.value)[0].status;
  console.log("状态", status);
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    status: status,
  };
  getCompetitionList(params);
};

//审核通过
const approve = (item) => {
  console.log(id)
  item.status = 1;
  competitionReview(item).then(function (response) {
    let status = tabs.filter((x) => x.value === currentTab.value)[0].status;
    let params = {
      id:item.id,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      status: status,
    };
    getCompetitionList(params);
  });
};

//审核不通过
const reject = (item) => {
  item.status = 2;
  competitionReview(item).then(function (response) {
    let status = tabs.filter((x) => x.value === currentTab.value)[0].status;
    let params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      status: status,
    };
    getCompetitionList(params);
  });
};

const setContentWidth = () => {
  if (contentDiv.value) {
    const windowWidth = window.innerWidth;
    contentDiv.value.style.width = `${windowWidth * 0.75}px`;
    contentDiv.value.style.marginLeft = `${windowWidth * 0.1}px`;
  }
};

onMounted(() => {
  setContentWidth();
  window.addEventListener('resize', setContentWidth);

  let status = tabs.filter((x) => x.value === currentTab.value)[0].status;
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    status: status,
  };
  getCompetitionList(params);
});
</script>
  

<style scoped>
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

th {
  background-color: #f9fafb;
  /* 对应bg-gray-50颜色 */
}

.bold-black {
  font-weight: bold;
  color: black;
}
</style>
    
    